<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Validator;
use DateTimeInterface;

class BaseModel extends Model
{
    // 修复时区晚8个小时的问题
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public static function formatPaged($page, $size, $total)
    {
        return [
            'total' => $total,
            'page' => $page,
            'size' => $size,
            'more' => ($total > $page * $size) ? 1 : 0
        ];
    }

    public static function formatBody(array $data = [], $message='')
    {
        $data['error_code'] = 0;
        $data['error_desc'] = !empty($message) ? $message : config('error.0');
        return $data;
    }

    public static function formatError($code, $message = null)
    {
        $body['error_code'] = $code;
        $body['error_desc'] = !empty($message) ? $message : config('error.'.$code);

        return $body;
    }

    /**
     * 获取随机字符串
     * @param int $randLength 长度
     * @param int $addtime 是否加入当前时间戳
     * @param int $includenumber 是否包含数字
     * @return string
     */
    public static function rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
    {
        if ($includenumber) {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
        } else {
            $chars = 'abcdefghijklmnopqrstuvwxyz';
        }
        $len = strlen($chars);
        $randStr = '';
        for ($i = 0; $i < $randLength; $i++) {
            $randStr .= $chars[mt_rand(0, $len - 1)];
        }
        $tokenvalue = $randStr;
        if ($addtime) {
            $tokenvalue = $randStr . time();
        }
        return $tokenvalue;
    }

    // 天数统计
    protected static function getCountDays($sTime, $eTime)
    {
        $startDt = getdate($sTime);

        $endDt = getdate($eTime);

        $sUTime = mktime(12, 0, 0, $startDt['mon'], $startDt['mday'], $startDt['year']);

        $eUTime = mktime(12, 0, 0, $endDt['mon'], $endDt['mday'], $endDt['year']);

        // 计算日期段内有多少天
        $days = ($eUTime-$sUTime)/86400+1;

        // 保存每天日期
        $date = [];

        for($i=0; $i<$days; $i++)
        {
            $date[] = date('Y-m-d', $sUTime+(86400*$i));
        }

        return $date;
    }

    function get_week($date){
        //强制转换日期格式
        $date_str=date('Y-m-d',strtotime($date));
        //封装成数组
        $arr=explode("-", $date_str);
        //参数赋值
        //年
        $year=$arr[0];
        //月，输出2位整型，不够2位右对齐
        $month=sprintf('%02d',$arr[1]);
        //日，输出2位整型，不够2位右对齐
        $day=sprintf('%02d',$arr[2]);
        //时分秒默认赋值为0；
        $hour = $minute = $second = 0;
        //转换成时间戳
        $strap = mktime($hour,$minute,$second,$month,$day,$year);
        //获取数字型星期几
        $number_wk=date("w",$strap);
        //自定义星期数组
        $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
        //获取数字对应的星期
        return $weekArr[$number_wk];
    }

}
